package com.fc.advbox.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fc.advbox.dao.BaseDao;
import com.fc.advbox.dao.OrgAcctDao;
import com.fc.advbox.dao.OrgAcctTxnDao;
import com.fc.advbox.entity.AdvOrgAcctEntity;
import com.fc.advbox.entity.AdvOrgAcctTxnEntity;
import com.fc.advbox.entity.AdvOrgMonthProfitEntity;
import com.fc.advbox.model.org.OrgMonthProfit;
import com.fc.advbox.service.IEquipmentDailyProfitService;
import com.fc.advbox.service.IOrgAcctService;
import com.fc.advbox.service.IOrgMonthProfitService;
import com.fc.advbox.service.IOrgService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.DateTimeHelper;
import com.fc.advbox.utils.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Description:
 * User: Charles.Gao
 * Date: 2018-06-27 13:10
 */
@Service("orgAcctService")
public class OrgAcctServiceImpl extends BaseServiceImpl<AdvOrgAcctEntity> implements IOrgAcctService {

    @Autowired
    private OrgAcctDao orgAcctDao;

    @Autowired
    private OrgAcctTxnDao orgAcctTxnDao;

    @Override
    public BaseDao getDao() {
        return orgAcctDao;
    }

    @Autowired
    private IEquipmentDailyProfitService equipmentDailyProfitService;

    @Autowired
    private IOrgMonthProfitService orgMonthProfitService;

    @Autowired
    private IOrgService orgService;

    @Override
    public void calculateOrgAccountProfit(Date currentDate)
    {
        Date previousMonthDate = DateTimeHelper.addMonth(currentDate, -1);
        List<OrgMonthProfit> orgMonthProfitList = equipmentDailyProfitService.queryAgentAndChannelMonthProfitList(previousMonthDate);
        if(orgMonthProfitList != null && !orgMonthProfitList.isEmpty())
        {
            for(OrgMonthProfit orgMonthProfit : orgMonthProfitList)
            {
                if(orgMonthProfit.getOrgId() == null)
                {
                    continue;
                }
                if(orgMonthProfit.getProfit() == null)
                {
                    orgMonthProfit.setProfit(BigDecimal.ZERO);
                }

                //  给代理商和渠道商的账户增加收益
                increaseOrgProfit(orgMonthProfit, currentDate);

                // 维护代理商和渠道商的月收益表记录
                maintainOrgMonthProfit(orgMonthProfit, previousMonthDate);
            }

        }
    }

    @Override
    public List<AdvOrgAcctTxnEntity> getAcctTxnByAcctId(Long acctId){
        Map<String,Object> query = new HashMap();
        query.put("acctId", acctId);
        if(acctId != null){
            return orgAcctTxnDao.queryList(query);
        }else{
            return new ArrayList();
        }
    }

    @Override
    public void intoCash(JSONObject jsonObject) {
        Long orgId = jsonObject.getLong("orgId");
        BigDecimal amount = jsonObject.getBigDecimal("amount");
        String comment = jsonObject.getString("comment");
        if(amount == null || amount.compareTo(BigDecimal.ZERO) <= 0)
        {
            return;
        }
        AdvOrgAcctEntity advOrgAcctEntity = orgAcctDao.queryByOrgId(orgId);
        if(advOrgAcctEntity == null)
        {
            throw new RRException("该组织账号不存在！");
        }

        if(advOrgAcctEntity.getBalance() == null || advOrgAcctEntity.getBalance().compareTo(amount) < 0)
        {
            throw new RRException("账号余额不足！");
        }

        // 账号余额减去体现金额
        advOrgAcctEntity.setBalance(advOrgAcctEntity.getBalance().subtract(amount));
        orgAcctDao.update(advOrgAcctEntity);

        // 交易记录
        AdvOrgAcctTxnEntity acctTxnEntity = new AdvOrgAcctTxnEntity();
        acctTxnEntity.setAcctId(advOrgAcctEntity.getId());
        acctTxnEntity.setTxnType(0);//0往账，1来账
        acctTxnEntity.setOrgId(orgId);
        acctTxnEntity.setAmount(amount);
        acctTxnEntity.setCreateTime(new Date());
        acctTxnEntity.setComments("[提现] " + (comment == null ? "" : comment));
        orgAcctTxnDao.save(acctTxnEntity);
    }

    @Override
    public AdvOrgAcctEntity queryByOrgId(Long orgId){
        return orgAcctDao.queryByOrgId(orgId);
    }

    private void increaseOrgProfit(OrgMonthProfit orgMonthProfit, Date currentDate) {
        AdvOrgAcctEntity advOrgAcctEntity = orgAcctDao.queryByOrgId(orgMonthProfit.getOrgId());
        if(advOrgAcctEntity == null)
        {
            // 新创建一个账号
            advOrgAcctEntity = new AdvOrgAcctEntity();
            advOrgAcctEntity.setOrgId(orgMonthProfit.getOrgId());
            advOrgAcctEntity.setBalance(BigDecimal.ZERO);
            advOrgAcctEntity.setProfit(orgMonthProfit.getProfit());
            advOrgAcctEntity.setStatus(Constant.Status.ENABLE.getValue());
            advOrgAcctEntity.setCreateTime(new Date());
            orgAcctDao.save(advOrgAcctEntity);
        }
        else
        {
            // 利润
            if(advOrgAcctEntity.getProfit() == null)
            {
                advOrgAcctEntity.setProfit(BigDecimal.ZERO);
            }
            advOrgAcctEntity.setProfit(advOrgAcctEntity.getProfit().add(orgMonthProfit.getProfit()));

            // 账户余额
            if(advOrgAcctEntity.getBalance() == null)
            {
                advOrgAcctEntity.setBalance(BigDecimal.ZERO);
            }
            advOrgAcctEntity.setBalance(advOrgAcctEntity.getBalance().add(orgMonthProfit.getProfit()));

            orgAcctDao.update(advOrgAcctEntity);
        }

        // 交易记录
        AdvOrgAcctTxnEntity acctTxnEntity = new AdvOrgAcctTxnEntity();
        acctTxnEntity.setAcctId(advOrgAcctEntity.getId());
        acctTxnEntity.setOrgId(orgMonthProfit.getOrgId());
        acctTxnEntity.setAmount(orgMonthProfit.getProfit());
        acctTxnEntity.setCreateTime(new Date());
        acctTxnEntity.setComments("广告收益[" + DateTimeHelper.getStringFromDate(currentDate, DateTimeHelper.PAYLOAD_DATEONLY) + "]");
        orgAcctTxnDao.save(acctTxnEntity);
    }

    /**
     * 维护代理商和渠道商月收益表
     * @param orgMonthProfit
     * @param previousMonthDate
     */
    private void maintainOrgMonthProfit(OrgMonthProfit orgMonthProfit, Date previousMonthDate)
    {
        JSONObject params = new JSONObject();
        params.put("orgId", orgMonthProfit.getOrgId());
        params.put("month", DateTimeHelper.getStringFromDate(previousMonthDate, DateTimeHelper.PAYLOAD_MONTH_ONLY));
        List<AdvOrgMonthProfitEntity> monthProfitEntityList = orgMonthProfitService.queryList(params);
        // 查询该月，该用户是否已经统计, 如果统计过则作更新操作
        if(monthProfitEntityList == null || monthProfitEntityList.isEmpty())
        {
            // 新增
            AdvOrgMonthProfitEntity entity = new AdvOrgMonthProfitEntity();
            entity.setOrgId(orgMonthProfit.getOrgId());
            entity.setOrgName(orgService.getOrgNameById(orgMonthProfit.getOrgId()));
            entity.setMonth(DateTimeHelper.getStringFromDate(previousMonthDate, DateTimeHelper.PAYLOAD_MONTH_ONLY));
            entity.setStartDateOfMonth(DateTimeHelper.getStartOfMonth(previousMonthDate));
            entity.setProfit(orgMonthProfit.getProfit());
            entity.setCreateTime(new Date());
            orgMonthProfitService.save(entity);
        }
        else
        {
            // 更新
            for (AdvOrgMonthProfitEntity entity : monthProfitEntityList)
            {
                entity.setOrgId(orgMonthProfit.getOrgId());
                entity.setOrgName(orgService.getOrgNameById(orgMonthProfit.getOrgId()));
                entity.setMonth(DateTimeHelper.getStringFromDate(previousMonthDate, DateTimeHelper.PAYLOAD_MONTH_ONLY));
                entity.setStartDateOfMonth(DateTimeHelper.getStartOfMonth(previousMonthDate));
                entity.setProfit(orgMonthProfit.getProfit());
                entity.setUpdateTime(new Date());
                orgMonthProfitService.update(entity);
            }
        }
    }
}
